import { Select2Page } from "../../../common/serve-request.js";
import stocktransferApi from '../../../common/api/cbs/stocktransfer.api.js';

(function (window, document, $) {
    let _vm, savetype, getEntryInfo = [], wareHouseMaterial
    $(function () {
        _vm = new Vue({
            el: "#saleordersentry-form",
            data() {
                return {
                    entries: [{
                        "seq": "",
                        "materialId": "",
                        "materialNumCode": "",
                        "materialName": "",
                        "materialUnit": "",
                        "materialModel": "",
                        "outQty": "",
                        "outPrice": "",
                        "inQty": "",
                        "inPrice": "",
                        "curQty": "",
                        "inAmount": 0,
                        "curQtyshow": ""
                    }]
                }
            },
            methods: {
                submit() {
                    if (!Utils.IsNotNull(_vm.entries[0]?.materialId)) {
                        return $.toptip(`请选择物料!`, 'warning');
                    }
                    if (!Utils.IsNotNull(_vm.entries[0]?.inQty)) {
                        return $.toptip(`请输入领用数量!`, 'warning');
                    }
                    if (!(/(^[1-9]\d*$)/.test(_vm.entries[0]?.inQty))) {
                        return $.toptip(`领用数量必须为大于0的整数!`, 'warning');
                    }
                    if (_vm.entries[0]?.inQty > _vm.entries[0]?.curQty) {
                        return $.toptip(`领用数量不能大于库存数量!`, 'warning');
                    }
                    savetips({ ..._vm.entries[0] })
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                if (params.isEdit == 'true') {
                    document.title = '物料领用分录 - 编辑'
                }
            },
        });

        _initCommand();
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
    });

    // 初始化数据
    const _initCommand = async () => {
        getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo")) || []
        let isEdit = JSON.parse(getUrlKey('isEdit'))
        let wid = getUrlKey('wid')
        let seq = getUrlKey('index')
        //查询物料
        wareHouseMaterial = await stocktransferApi.getHouseToMatrlsList(wid)
        _select2('materialId')
        $('#materialId').on("select2:select", async function () {
            let selectMaterial = $('#materialId').select2('data')[0]
            _vm.entries[0].materialId = selectMaterial?.id
            _vm.entries[0].materialName = selectMaterial?.name
            _vm.entries[0].materialNumCode = selectMaterial?.numCode
            _vm.entries[0].materialModel = selectMaterial?.model
            _vm.entries[0].materialUnit = selectMaterial?.baseMeasureUnit

            //查询即时库存物料价格
            let _res = _vm.entries[0].materialNumCode
            if (Utils.IsNotNull(_res)) {
                if (_res.substring(0, 2) == "03") { //饲料03
                    await _curMaterialInfo(_res.substring(0, 2));
                    await _breedbatchfeedprices();
                } else {
                    await _curMaterialInfo();
                }
            }
        })
        $('#inQtyVal').on('change', function () {
            if (Utils.IsNotNull(_vm.entries[0].inPrice)) {
                _vm.entries[0].inAmount = Utils.toThousands(_vm.entries[0].inQty * _vm.entries[0].inPrice, 2)
            }
            else {
                _vm.entries[0].inAmount == ''
            }
        })


        // 编辑时赋值
        if (isEdit) {
            let datas = getEntryInfo.find(item => item.seq == seq)
            _vm.entries[0].materialId = datas?.materialId
            _vm.entries[0].materialName = datas?.materialName
            _vm.entries[0].materialNumCode = datas?.materialNumCode
            _vm.entries[0].materialModel = datas?.materialModel
            _vm.entries[0].materialUnit = datas?.materialUnit
            _vm.entries[0].outQty = datas?.outQty
            _vm.entries[0].outPrice = datas?.outPrice
            _vm.entries[0].inQty = datas?.inQty
            _vm.entries[0].inPrice = datas?.inPrice

            _vm.entries[0].curQty = datas?.curQty
            _vm.entries[0].curQtyshow = Utils.toThousands(datas?.curQty, 0)

            _vm.entries[0].inAmount = datas?.inAmount
            $('#materialId').setSelectValue(datas?.materialId, datas?.materialName)

        }
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../stocktransfer/addstocktransfer.html?v=${Utils.GetTime()}`;
        });
    }

    //查询批次饲料价格详情By批次Id
    const _breedbatchfeedprices = async () => {
        let bid = getUrlKey('bid')
        let feedprices = await stocktransferApi.getFeedPrices(bid);
        let _feedPriceInfo = feedprices?.entries || 0;
        if (Utils.IsNotNull(_feedPriceInfo)) {
            let result = _feedPriceInfo.find(s => s.materialNumCode == _vm.entries[0].materialNumCode);
            _vm.entries[0].inPrice = result?.price

            _vm.entries[0].outPrice = result?.price
            if (Utils.IsNotNull(_vm.entries[0].inPrice)) {
                _vm.entries[0].inAmount = Utils.toThousands(_vm.entries[0].inQty * _vm.entries[0].inPrice, 2)
            }
            else {
                _vm.entries[0].inAmount == ''
            }
        } else {
            _vm.entries[0].inPrice = ''
            _vm.entries[0].outPrice = ''
            _vm.entries[0].inAmount = ''
        }
    }
    //查询即时库存物料价格
    const _curMaterialInfo = async (_res) => {
        let info = {
            "warehouseId": getUrlKey('wid'),
            "bizDate": getUrlKey('biz'),
            "materialId": _vm.entries[0].materialId,
            "materialName": _vm.entries[0].materialName
        }
        if (Utils.IsNotNull(_vm.entries[0].materialId)) {
            let materialPrice = await stocktransferApi.postCurinventoryPrice(_vm.entries[0].materialId, info);
            _vm.entries[0].curQty = materialPrice.curQty
            _vm.entries[0].curQtyshow = Utils.toThousands(materialPrice.curQty, 0)

            // 不是饲料
            if (!Utils.IsNotNull(_res)) {
                _vm.entries[0].inPrice = materialPrice?.price
                _vm.entries[0].outPrice = materialPrice?.costPrice
                if (Utils.IsNotNull(_vm.entries[0].inPrice)) {
                    _vm.entries[0].inAmount = Utils.toThousands(_vm.entries[0].inQty * _vm.entries[0].inPrice, 2)
                }
                else {
                    _vm.entries[0].inAmount == ''
                }
            }
        } else {
            _vm.entries[0].curQty = ''
            _vm.entries[0].inPrice = ''
            _vm.entries[0].outPrice = ''
            _vm.entries[0].inAmount = ''
        }
    }
    const _select2 = (id, json) => {
        Select2Page($(`#${id}`), `${Utils.CurDomain.MasterDataUrl}/yymaterials/q`, (params) => {
            return ({
                SearchInfo: params.term,
                PageSize: 10,
                PageIndex: (params.page || 1) - 1
            })
        }, "GET", {
            allowClear: true,//允许清空
            placeholder: '请选择物料...', //默认文字提示
            templateResult: function (res) {
                let flag = wareHouseMaterial.some(item => res.id == item.materialId)
                if (Utils.IsNotNull(res.id) && flag == true) {
                    let sltHtml = {
                        id: res.id,
                        text: res.name,
                        name: res.name,
                        model: res.model,
                        numCode: res.numCode,
                        baseMeasureUnit: res.baseMeasureUnit,
                        subMeasureUnit: res.subMeasureUnit,
                        textString: res.name + "," + res.numCode + "," + res.model + "," + res.baseMeasureUnit,
                        ...res
                    }

                    let sltSpanHtml = "";
                    if (!res.id) {
                        return "";
                    }
                    let arr = sltHtml?.textString?.split(',');
                    if (!arr) return;
                    res.id == -1 ? "" : sltSpanHtml +=
                        `<div style='margin-bottom: 8px;color:#000'>${arr[0]}</div>
                    <label style='font-size:0'>
                    <span style="border: #3e8ef7 1px solid;background-color: #fff;padding : 2px 4px;color:#3e8ef7;font-size: 9px;border-radius: 10px 0 0 10px">${arr[1]}</span>
                    <span style="border: #8A5082 1px solid;background-color: #8A5082;; padding : 2px 4px;color:#fff;font-size: 9px;">${arr[2]}</span>
                    <span style="border: #758EB7 1px solid;background-color: #758EB7;; padding : 2px 4px;color:#fff;font-size: 9px;border-radius: 0 10px 10px 0;">${arr[3]}</span>
                    </label>`;
                    return $(`<span data-code = "${arr[1]}" data-name="${arr[0]}" data-model = "${arr[2]}" data-unit = "${arr[3]}">${sltSpanHtml}</span>`);
                }
            }
        });

        $(`#${id}`).setSelectValue();
        $(`#${id}`).prop('disabled', false);
        //编辑回显
        if (Utils.IsNotNull(json)) {
            $(`#${id}`).setSelectValue(json.id, json.name);
        }
    }
    // 保存提示
    const savetips = (data) => {
        let saveEntry
        if (Utils.IsNotNull(getUrlKey("operaEntryId"))) {
            savetype = '修改'
            saveEntry = getUrlKey("operaEntryId")
        }
        else {
            savetype = '保存'
            saveEntry = getUrlKey('nextEntryId')
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
    				<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
    					<div>是否确认${savetype}该分录？</div>
    				</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        let seq = parseInt(getUrlKey('index'))
                        let isEdit = JSON.parse(getUrlKey('isEdit'))
                        // 新增
                        if (Utils.IsNotNull(getEntryInfo) && isEdit == false) {
                            getEntryInfo.push(data)
                        } else if (Utils.IsNotNull(getEntryInfo) && isEdit == true) {
                            // 编辑
                            getEntryInfo[seq] = data
                        } else {
                            getEntryInfo.push(data)
                        }
                        getEntryInfo.map((item, index) => {
                            item.seq = index
                            item.outQty = item.inQty
                        })
                        console.log(getEntryInfo)
                        // 存入SessionStorage
                        JSON.stringify(Utils.SetSessionStorage("getEntryInfo", getEntryInfo))
                        location.href = `./addstocktransfer.html?v=${Utils.GetTime()}`;
                        $.closeModal();
                    }
                }
            ]
        });
    }

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

})(window, document, jQuery)